//引入express
import express from "express";
import { respone } from '../../utils/respone.js';
import { uploadToQiniu } from "../../utils/uploads.js";
import { uploads } from '../../middleware/mluter.js'
import path from "path";
import db from '../../db/index.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { verifyToken } from '../../middleware/verifyToken.js';
import { checkallactive } from '../../middleware/checkallactive.js';


// 此中间件只能用于登录路由
import { checkactive } from '../../middleware/checkactive.js';



const router = express.Router()


// 注册路由
router.post("/register", async (req, res) => {
    try {
        // 获取用户名和密码
        const { telephone, password } = req.body;
        if (!telephone || !password) {
            return respone(res, 401, "请输入用户名和密码")
        }
        // 判断手机号是否存在
        const existingUser = await db('user').where({ telephone }).first();
        if (existingUser) return respone(res, 401, "手机号已存在")
        // 对密码进行加密
        const hashedPassword = await bcrypt.hash(password, 10);
        // 如果手机号不存在，创建新用户并插入数据库
        await db('user').insert({ telephone, password: hashedPassword });

        // 返回成功信息
        return respone(res, 200, "用户注册成功");
    } catch (error) {
        return respone(res, 500, error.message);
    }
})


// 登录路由
router.post("/login", checkactive, async (req, res) => {
    try {
        // 获取用户名和密码
        const { telephone, password } = req.body;
        if (!telephone || !password) {
            return respone(res, 401, "请输入手机号和密码")
        }
        // 判断手机号是否存在
        const existingUser = await db('user').where({ telephone }).first();
        if (!existingUser) return respone(res, 401, "手机号不存在")
        // 判断密码是否正确
        const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
        if (!isPasswordCorrect) return respone(res, 401, "密码错误")
        // 生成token
        const token = jwt.sign({ telephone }, "139766", { expiresIn: "72h" })
        // 返回成功信息
        return respone(res, 200, "用户登录成功", { token });
    } catch (error) {
        return respone(res, 500, error.message);
    }
})


// 获取用户信息路由
router.get('/info', verifyToken, checkallactive, async (req, res) => {
    try {
        const { telephone } = req.user;
        // 从数据库中获取用户信息
        const { user_id, user_img } = await db('user').where({ telephone }).first();
        return respone(res, 200, "获取用户信息成功~", { user: { user_id, telephone, user_img } })
    } catch (error) {
        return respone(res, 500, error.message)
    }
})

// 上传头像路由
router.post('/upload', verifyToken, uploads.single('headimg'), async (req, res) => {
    try {
        const file = req.file;
        // 生成文件名
        const key = Date.now() + path.extname(file.originalname);
        const { telephone } = req.user;
        // 将本地文件上传到七牛云
        const url = await uploadToQiniu(file.path, key);
        // 插入数据库
        await db('user').where({ telephone }).update({ user_img: url });
        respone(res, 200, '上传成功', { url });
    } catch (error) {
        throw new Error(error.message);
    }
})


//暴露路由
export default router;